const path = require('path')
const { defineConfig } = require('rollup')
const json = require('@rollup/plugin-json')
const alias = require('@rollup/plugin-alias')
const terser = require('@rollup/plugin-terser')
const commonjs = require('@rollup/plugin-commonjs')
const typescript = require('@rollup/plugin-typescript')
const nodeResolve = require('@rollup/plugin-node-resolve')
const dts = require('rollup-plugin-dts').default
const { buildOutputPath } = require('../config')
const replace = require('@rollup/plugin-replace')

const entryFile = path.resolve(__dirname, '../../src/cli/index.ts')
const outputDir = buildOutputPath

// 路径别名配置
const aliasConfig = require('./alias')

const tsconfig = require('./tsconfig')

module.exports = defineConfig([
  {
    input: entryFile, // 入口文件路径
    output: {
      file: path.resolve(outputDir, 'cli.js'),
      format: 'cjs'
    },
    plugins: [
      typescript(tsconfig),
      nodeResolve({
        preferBuiltins: true
      }),
      commonjs(),
      json(),
      terser({
        format: {
          comments: false, // 注释是否保留注释
          beautify: true // 保留代码格式
        },
        mangle: false // 代码混淆
      }),
      alias(aliasConfig),
      replace({
        __env__: '"production"',
        preventAssignment: true
      })
    ],
    external: [],
    onwarn(warning, warn) {
      // 禁用 "Circular dependencies" 警告
      if (warning.code === 'CIRCULAR_DEPENDENCY') return

      // 正常显示其他警告
      warn(warning)
    },
    treeshake: true
  },
  // 打包暴露文件
  {
    input: path.resolve(__dirname, '../../src/index.ts'),
    output: {
      file: path.resolve(outputDir, 'index.js'),
      format: 'cjs'
    },
    plugins: [typescript(tsconfig), alias(aliasConfig)]
  },
  // 打包类型声明文件
  {
    input: path.resolve(__dirname, '../../src/index.ts'),
    output: {
      file: path.resolve(outputDir, 'index.d.ts')
    },
    plugins: [dts(), alias(aliasConfig)]
  }
])
